#include "head.h"

int putsFunc(int sockfd, const char *filename) {
    // train_t train;
    // bzero(&train, sizeof(train));
    // int fd = open(filename, O_RDWR);

    // struct stat statbuf;
    // fstat(fd,&statbuf);
    // printf("filesize = %ld\n", statbuf.st_size);
    // train.length = sizeof(statbuf.st_size);
    // memcpy(train.data,&statbuf.st_size,train.length);
    // send(sockfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
    // sendfile(sockfd,fd,NULL,statbuf.st_size);

    // 先接收报错
    int ifError;
    recvn(sockfd, &ifError, sizeof(int));
    if (ifError != 0) {
        // 接收一个小火车
        print_network_message(sockfd);
        return -1;
    }

    train_t train_file;
    bzero(&train_file, sizeof(train_file));

    char MD5[128] = {0};
    getFileMD5(filename, MD5);
    strcpy(train_file.data, MD5);
    train_file.length = strlen(MD5);
    send(sockfd, &train_file, sizeof(int)+train_file.length, MSG_NOSIGNAL);

    printf("upload begin\n");

    recvn(sockfd, &ifError, sizeof(int));
    if(ifError == 888){
        bzero(&train_file, sizeof(train_t));
        recvn(sockfd, &train_file.length, sizeof(int));
        recvn(sockfd, train_file.data, train_file.length);
        puts(train_file.data);
        return -1;
    }

    int ret;
    recvn(sockfd, &ret, sizeof(int));
    if(ret == 999){
        printf("秒传成功\n");
        return 0;
    }

    int fd = open(filename, O_RDWR);
    struct stat statbuf;
    fstat(fd, &statbuf);
    // train_file.length=sizeof(statbuf.st_size);
    // memcpy(train_file.data, &statbuf.st_size, train_file.length);
    // send(sockfd, &train_file, sizeof(train_file.length)+train_file.length, MSG_NOSIGNAL);
    // bzero(&train_file, sizeof(train_file));
    while(1){
        bzero(&train_file, sizeof(train_file));
        ssize_t sret=read(fd,train_file.data,sizeof(train_file.data));
        if(sret==0){
            printf("upload over\n");
            break;
        }
        train_file.length = sret;
        sret = send(sockfd,&train_file,sizeof(train_file.length)+train_file.length,MSG_NOSIGNAL);
    }
    train_file.length=0;
    send(sockfd,&train_file,sizeof(train_file.length),MSG_NOSIGNAL);
    // 报错信息呢
    //
    //
    //
    //
    // 写前面
    close(fd);
    return 0;
}
